package service

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/medivhzhan/weapp/v2"
	"github.com/rs/zerolog/log"
	"h8QuestionnaireServer/components/config"
	"h8QuestionnaireServer/database/dao"
	"h8QuestionnaireServer/database/entity"
	"h8QuestionnaireServer/pojo/request"
)

func Login(code string) (user *entity.AccountInfo, err error) {
	log.Info().Msgf("微信小程序准备登陆，code=%s", code)
	wxResp, err := weapp.Login(config.Config.Wxapp.Appid, config.Config.Wxapp.Secret, code)
	if err != nil {
		log.Info().Msgf("wxapp login err %v", err)
		return
	}

	if wxResp.OpenID == "" {
		log.Info().Msgf("wxapp login err %v", wxResp.CommonError)
		return
	}
	user, err = dao.FindUserByOpenId(wxResp.OpenID)
	if gorm.IsRecordNotFoundError(err) {
		// 获取详尽用户信息
		// res, err := weapp.GetPaidUnionID(wxapp.GetAccessToken(), wxResp.OpenID, "transaction-id")
		// 不存在
		user, err = dao.InsertAccount(wxResp.OpenID, wxResp.UnionID)
		return
	}
	return
}

func SaveAccount(openid string, param request.WxAccountInfo) (user *entity.AccountInfo, err error) {
	fmt.Printf("nickname=%s", param.Nickname)
	return
}

func SaveAccountInfo(openid, unionid string)  {
	dao.InsertAccount(openid, unionid)
}
